import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: { title: '登录' }
    },
    {
      path: '/',
      name: 'Layout',
      component: () => import('@/layout/index.vue'),
      redirect: '/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('@/views/Dashboard.vue'),
          meta: { title: '首页', icon: 'HomeOutlined' }
        },
        {
          path: 'student',
          name: 'Student',
          component: () => import('@/views/Student/index.vue'),
          meta: { title: '学生管理', icon: 'UserOutlined' }
        },
        {
          path: 'building',
          name: 'Building',
          component: () => import('@/views/Building/index.vue'),
          meta: { title: '宿舍楼管理', icon: 'BankOutlined' }
        },
        {
          path: 'room',
          name: 'Room',
          component: () => import('@/views/Room/index.vue'),
          meta: { title: '房间管理', icon: 'HomeOutlined' }
        },
        {
          path: 'repair',
          name: 'Repair',
          component: () => import('@/views/Repair/index.vue'),
          meta: { title: '报修管理', icon: 'ToolOutlined' }
        },
        {
          path: 'attendance',
          name: 'Attendance',
          component: () => import('@/views/Attendance/index.vue'),
          meta: { title: '考勤管理', icon: 'CheckCircleOutlined' }
        },
        {
          path: 'notice',
          name: 'Notice',
          component: () => import('@/views/Notice/index.vue'),
          meta: { title: '公告管理', icon: 'NotificationOutlined' }
        },
        {
          path: 'user',
          name: 'User',
          component: () => import('@/views/User/index.vue'),
          meta: { title: '用户管理', icon: 'TeamOutlined' }
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  if (to.path === '/login') {
    if (token) {
      next('/')
    } else {
      next()
    }
  } else {
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router

